//
//  OrderPayRequestHandle.m
//  sensen_ios
//
//  Created by pro on 16/3/23.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "OrderPayRequestHandle.h"

@implementation OrderPayRequestHandle

+ (void)requestPayModel:(AliPayModel *)payModel
                success:(void(^)(NSDictionary *dic))success
                  error:(void(^)(NSString *error))error {
    
    NSString *orderSpec = [payModel description];
    
    id<DataSigner> signer = CreateRSADataSigner(GLOBAL_ALIPAY_PRIVATE_KEY);
    NSString *signedString = [signer signString:orderSpec];
    //将签名成功字符串格式化为订单字符串,请严格按照该格式
    NSString *orderString = nil;
    
    if (signedString != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        NSLog(@"%@", orderString);

        [[AlipaySDK defaultService] payOrder:orderString fromScheme:APP_SCHEME callback:^(NSDictionary *resultDic) {
            
//            NSLog(@"支付结果打印:%@", resultDic);
            
            /**
             *  发起国际支付宝请求
             *  成功与失败的传入值：NSDictionary 中的key如下
             *  resultStatus = 返回的结果 编码
             *  success = 成功时会有值,失败时null
             *  memo = 错误时，返回的错误信息
             *  result = 返回的支付相关的信息，一般用不到
             *  sign = 签名串，暂时不用管
             */
            
            NSString * resultStatus =[resultDic valueForKey:@"resultStatus"];
            NSString * memo =[resultDic valueForKey:@"memo"];
//            NSString * sign =[resultDic valueForKey:@"sign"];
            
            /*
             9000 表示支付成功
             8000 正在处理中
             4000 订单支付失败
             6001 用户中途取消
             6002 网络连接出错
             */
            
            if ([resultStatus isEqualToString:@"9000"] ) {
                if (success) {
                    success(resultDic);
                } else {
                    [SVProgressHUD showSuccessWithStatus:@"支付成功!" withDuration:2];
                }
            } else {
                
                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"支付失败: %@,code=%@",memo,resultStatus] withDuration:2.5];
                if (error) {
                    error(@"支付失败");
                }
            }
            
        }];
        
    } else {
        [SVProgressHUD showErrorWithStatus:@"发起支付失败,签名为空!"];
    }

    
    
    
}

@end
